<script setup>
import { ref, watch } from "vue";
import { getUId } from "@/utils";
import {
  PlusCircleOutlined,
  DeleteOutlined,
  SaveOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import i18n from '@/locales/index' 
const { t } = i18n.global

const props = defineProps({
  operateType: String,
  data: Array,
  stationList: Array,
});

const emits = defineEmits(["onTreeData"]);

const findTreeNode = (tree, target, field = "key") => {
  for (let i = 0; i < tree.length; i++) {
    if (tree[i][field] === target) {
      return tree[i];
    }
    if (tree[i].children && tree[i].children.length) {
      const res = findTreeNode(tree[i].children, target, field);
      if (res) {
        return res;
      }
    }
  }
};

const findTreeNodeParent = (tree, target, field = "key") => {
  for (let i = 0; i < tree.length; i++) {
    if (tree[i].children && tree[i].children.length) {
      const flag = tree[i].children.some((item) => item[field] === target);
      if (flag) {
        return tree[i];
      }
      if (!flag) {
        const res = findTreeNodeParent(tree[i].children, target, field);
        if (res) {
          return res;
        }
      }
    }
  }
};
const dataKeys = (arr, key) => {
  const newArr = [];
  arr.forEach((item) => {
    newArr.push(item[key]);
  });
  return newArr;
};
// const treeOptions = [
//   { label: "a", value: "1" },
//   { label: "b", value: "2" },
//   { label: "c", value: "3" },
//   { label: "d", value: "4" },
//   { label: "e", value: "5" },
//   { label: "f", value: "6" },
//   { label: "g", value: "7" },
// ];

const selectVal = ref();
const selectInfo = ref({});

// const getOptionLabel = (options, value, key) => {
//   const target = options.find((item) => item.value === value);
//   return target[key];
// };

const treeData = ref(props.data);

const expandedKeys = ref([]);

const onSelect = (selectedKeys, info) => {
  console.log("selected", selectedKeys, info);
};

const treeItemClick = (event, key, type) => {
  try {
    event.preventDefault();
    event.stopPropagation();
    const treeNode = findTreeNode(treeData.value, key);
    // console.log(treeNode, "----treeNode----");
    // 保存处理
    if (type === "save") {
      if (selectInfo.value.lineNo && selectVal.value) {
        Object.assign(treeNode, selectInfo.value);
        treeNode["title"] =
          selectInfo.value.lineNo + "-" + selectInfo.value.label;
        treeNode["label"] = selectInfo.value.lineNo + "-" + selectVal.value;
        treeNode["type"] = null;
        treeNode["nodeType"] = "add";
        treeNode["add"] = true;

        // treeNode["lineNo"] = selectInfo.value.lineNo;
        // treeNode["role"] = selectInfo.value.roleName;
        // treeNode["stationId"] = selectInfo.value.stationId;
        // treeNode["stationNo"] = selectVal.value;
        emits("onTreeData", treeData.value);
      } else {
        message.warning(t('components.pleaseSelectStation'));
      }
    }
    // 删除处理
    if (type === "del") {
      // console.log("站位", key);
      const parent = findTreeNodeParent(treeData.value, key);
      parent.children = parent.children.filter((item) => item.key !== key);
      emits("onTreeData", treeData.value);
    }
    // 新增处理
    if (type === "add") {
      // console.log(event, key, type);
      treeNode.children.push({
        title: undefined,
        isLeaf: true,
        key: getUId(),
        type: "select",
      });
    }
    selectVal.value = null;
    selectInfo.value = {};
  } catch (err) {
    console.log(err);
  }
};

const selectChange = (val, option) => {
  // console.log(option, "-----option----");
  selectVal.value = val;
  selectInfo.value = option;
};
defineExpose({
  treeData,
});
watch(
  () => props.data,
  (data) => {
    treeData.value = data;
    expandedKeys.value = dataKeys(data, "key");
  },
  {
    deep: true,
  }
);
</script>
<template>
  <div class="rightTree">
    <div class="title">{{$t('hangManage.roadList')}}</div>
    <div class="treeShow">
      <a-tree
        v-model:expandedKeys="expandedKeys"
        :show-line="true"
        :tree-data="treeData"
        @select="onSelect"
      >
        <template
          #title="{
            title,
            // isLeaf,
            key,
            type,
            processId,
            processDetailId,
            stationId,
            add,
            // ...args
          }"
        >
          <span v-if="stationId || add" class="treeItem">
            <span>{{ title }}</span>
            <a-tooltip
              v-if="props.operateType != 'view'"
              placement="top"
              :title="$t('common.del')"
              arrow-point-at-center
            >
              <DeleteOutlined
                @click="(event) => treeItemClick(event, key, 'del')"
              />
            </a-tooltip>
          </span>
          <span v-if="type === 'select'" class="treeItem">
            <a-select
              class="treeSelect"
              @change="selectChange"
              :options="stationList"
              :fieldNames="{
                label: 'label',
                value: 'stationNo',
              }"
              :placeholder="$t('common.pleaseSelect')"
            ></a-select>
            <a-tooltip placement="top" :title="$t('common.save')" arrow-point-at-center>
              <SaveOutlined
                @click="(event) => treeItemClick(event, key, 'save')"
              />
            </a-tooltip>
          </span>
          <template
            v-if="props.operateType == 'add' ? processId : processDetailId"
          >
            <div class="treeItem">
              <span :title="title">{{ title }}</span>
              <a-tooltip
                v-if="props.operateType != 'view'"
                placement="top"
                :title="$t('components.addStation')"
                arrow-point-at-center
              >
                <PlusCircleOutlined
                  @click="(event) => treeItemClick(event, key, 'add')"
                />
              </a-tooltip>
            </div>
          </template>
        </template>
      </a-tree>
    </div>
  </div>
</template>

<style scoped lang="less">

</style>
